package com.autoplaza;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.autoplaza.ListaUbicacion.CargarInfo;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListaPrecio extends ListActivity {

	String result, marcaseleccionada, modeloseleccionado, sb5, anoseleccionado,ubicacionseleccionada,variable,content;
	InputStream is = null;
	String[] arr2,array2, array4;
	private LayoutInflater mInflater;
	private Vector<RowData> data;
	String textoEnviar, textoEnviar2 ;
	String cadena, cadena2;
	int suma = 0;
	private int bandera=0;
	private String sb9;
	private ProgressDialog progressDialog;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.listaprecio);
		
		int size = Utils.getScreenSize2(ListaPrecio.this);
		if( size == 1){
			LinearLayout lin = (LinearLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(30, 30));
		}		
		if( size == 2){
			LinearLayout lin = (LinearLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 60));	
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(45, 45));

		}		
		if( size == 3){
			LinearLayout lin = (LinearLayout) findViewById(R.id.linearLayout1);
			lin.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 80));
//			btnmenu.setLayoutParams(new LinearLayout.LayoutParams(80, 80));

		}
		
		if(isOnline()){
			new CargarInfo().execute("");
		}else{
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(R.string.necesita_conexi_n_a_internet)
			.setCancelable(false)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					finish();
					}
			});
			AlertDialog alertDialog = builder.create();
			alertDialog.show();
		}
		
 
	}
	
	private class RowData {
	    protected String mItem;
	        protected String mDescription;
	        RowData(String item, String description){
	        mItem = item;
	        mDescription = description;             
	    }

	        @Override
	        public String toString() {
	                return mDescription + " " +   mItem;
	        }
	}
	
	private class CustomAdapter extends ArrayAdapter<RowData> {
        public CustomAdapter(Context context, int resource,
                        int textViewResourceId, List<RowData> objects) {
                super(context, resource, textViewResourceId, objects);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder holder = null;

                //widgets displayed by each item in your list
                TextView item = null;
                TextView description = null;

                //data from your adapter
                RowData rowData= getItem(position);

                //we want to reuse already constructed row views...
                if(null == convertView){
                        convertView = mInflater.inflate(R.layout.custom_row2, null);
                        holder = new ViewHolder(convertView);
                        convertView.setTag(holder);
                }
                holder = (ViewHolder) convertView.getTag();
                if(position==0){
                    item = holder.getItem();
                    item.setText(rowData.mItem);
                    item.setTextSize(19);
        			item.setTextColor(Color.WHITE);

                    description = holder.getDescription();          
                    description.setText(rowData.mDescription);
                    description.setTextSize(16);
        			description.setTextColor(Color.WHITE);
                	
                }else{
                    item = holder.getItem();
                    item.setText(rowData.mItem.substring(2, rowData.mItem.length()));
                    item.setTextSize(19);
        			item.setTextColor(Color.WHITE);

                    description = holder.getDescription();          
                    description.setText(rowData.mDescription);
                    description.setTextSize(16);
        			description.setTextColor(Color.WHITE);
                }

                return convertView;
        }
}
	private class ViewHolder {      
	    private View mRow;
	    private TextView description = null;
	    private TextView item = null;

	        public ViewHolder(View row) {
	        mRow = row;
	        }

	        public TextView getDescription() {
	                if(null == description){
	                        description = (TextView) mRow.findViewById(R.id.item);
	                }
	                return description;
	        }

	        public TextView getItem() {
	                if(null == item){
	                        item = (TextView) mRow.findViewById(R.id.description);
	                }
	                return item;
	        }       
	}
	
	public void onBackPressed() {
		if(bandera == 0){
			SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = preferences.edit();
			editor.putString("precio", "[Cualquiera]");
				editor.putString("content", content);
				editor.commit();
				finish();
		}else if(bandera == 7){
			SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = preferences.edit();
			SharedPreferences preferences2= getSharedPreferences("Carro",Context.MODE_PRIVATE);
			SharedPreferences.Editor editor2 = preferences2.edit();
			editor2.putInt("flag", 0);
			editor2.putInt("pref", 0);
			editor2.putInt("offset", 0);
			editor2.commit();
//			editor.putString("precio", "[Cualquiera]");
//			editor.commit();
			finish();
//			Intent resultados=new Intent(ListaPrecio.this, Resultados.class);
//			resultados.putExtra("sb9", ""+sb9);
//			startActivity(resultados);
		}
		
	}
	
	public void onListItemClick(ListView parent, View v, int position, long id) {
		if(bandera==0){
			 CustomAdapter adapter = (CustomAdapter) parent.getAdapter();
		        SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
				SharedPreferences.Editor editor = preferences.edit();
				if(position==0){
					editor.putString("precio", "[Cualquiera]");
					editor.putString("content", content);
					editor.commit();
					finish();
				}else{
				editor.putString("precio", array2[position]);
				editor.putString("content", content);
				editor.commit();
				finish();
				}
		}else if(bandera == 7){
			SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = preferences.edit();
			SharedPreferences preferences2= getSharedPreferences("Carro",Context.MODE_PRIVATE);
			SharedPreferences.Editor editor2 = preferences2.edit();
			editor2.putInt("flag", 0);
	        editor2.putInt("pref", 0);
			editor2.putInt("offset", 0);
			editor2.commit();
			
			
			if(position==0){
				editor.putString("precio", "[Cualquiera]");
				editor.commit();

				Intent resultados=new Intent(ListaPrecio.this, Resultados.class);
				resultados.putExtra("sb9", ""+sb9);
				startActivity(resultados);
			}else{
				editor.putString("precio", array2[position]);
				Log.i("PREF PRECIO", ""+array2[position]);
				editor.commit();
				finish();
//				String url=funcionUrl();
//				Intent resultados = new Intent(ListaPrecio.this, Resultados.class);
//				resultados.putExtra("sb9", url);
//				startActivity(resultados);
			}
		}
	   
	}
	
	private String funcionUrl() {
		StringBuilder sb = new StringBuilder();
		sb.append("http://iphone.autoplaza.com.mx/fastSearch/fastSearchIphone.aspx?querybiphone=yes&BusqMult=");
		SharedPreferences preferences= getSharedPreferences("Carro",Context.MODE_PRIVATE);
		if(!(preferences.getString("marca", "")).equals("[Cualquiera]")){
			sb.append(":marca;"+preferences.getString("marca", "").replaceAll(" ", "%20"));
		}
		if(!(preferences.getString("modelo", "")).equals("[Cualquiera]")){
			sb.append(":modelo;"+preferences.getString("modelo", "").replaceAll(" ", "%20"));
		}
		if(!(preferences.getString("ano", "")).equals("[Cualquiera]")){
			sb.append(":year;"+preferences.getString("ano", "").replaceAll(" ", "%20"));
		}
		if(!(preferences.getString("ubicacion", "")).equals("[Cualquiera]")){
			sb.append(":estado;"+preferences.getString("ubicacion", "").replaceAll(" ", "%20"));
		}
		if(!(preferences.getString("precio", "")).equals("[Cualquiera]")){
			sb.append(":rankprecio;"+preferences.getString("precio", "").replaceAll(" ", "%20"));
		}
		if(!(preferences.getString("transmision", "")).equals("[Cualquiera]")){
			sb.append(":tipotransmision;"+preferences.getString("transmision", "").replaceAll(" ", "%20"));
		}
		if(!(preferences.getString("color", "")).equals("[Cualquiera]")){
			sb.append(":colorexterior;"+preferences.getString("color", "").replaceAll(" ", "%20"));
		}
		if(!(preferences.getString("financiamiento", "[Cualquiera]")).equals("[Cualquiera]")){
			sb.append(":tieneplanfid;"+preferences.getString("financiamiento", "").replaceAll(" ", "%20"));
		}
		if(!(preferences.getString("version", "")).equals("[Cualquiera]")){
			sb.append(":version;"+preferences.getString("version", "").replaceAll(" ", "%20"));
		}
		sb.append("&titlebiphone=yes&offset=0&hits=10&VIP=yes");
		Log.i("CADENA BUSQUEDA", ""+sb.toString());
		return sb.toString();
	}
	
	protected void organizararray(String sb52) {
		 String url=sb52;
	        Log.i("url mia", ""+url);
			URI myURI = null;
			try {
				myURI = new URI(url);
			} catch (URISyntaxException e) {
			}
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet getMethod = new HttpGet(myURI);
			HttpResponse webServerResponse = null;
			try {
				webServerResponse = httpClient.execute(getMethod);
			}  catch (IOException e) {
			}
			
			HttpEntity httpEntity = webServerResponse.getEntity();
	       
			//MANEJO DE LA RESPUESTA DEL SERVIDOR
			
			if (httpEntity != null) {
		
				try {
					is = httpEntity.getContent();
					BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
		            StringBuilder sb = new StringBuilder();
		            String line = null;
		            while ((line = reader.readLine()) != null) {
		                    sb.append(line + "\n");
		            }
		            is.close();
		            result=sb.toString();
		            String array[]=result.split("%%%");
		            Log.i("result", ""+result);
		            
		            ArrayList<String> lista = new ArrayList<String>();  
		            for(int i = 0; i < array.length; i++){ 
		              lista.add(array[i]); 
		            } 

		            Collections.sort(lista); 
		            Log.i("ORDEN", ""+lista);

		            for(int i=0; i<array.length; i++){
		            	Log.i("MI ARRAY1", ""+array[i]);
		            }
		 
		            array2 = new String[lista.size()];
		            array4 = new String[lista.size()];

		            for(int i=0; i<lista.size(); i++){
		            	String[] array3=lista.get(i).toString().split("@@@");
		            	array2[i]=array3[0];
		            	Log.i("MI ARRAY2", ""+array2[i]);
		            }
		            
		            for(int i=1; i<lista.size(); i++){
	            	String[] array3=lista.get(i).toString().split("@@@");
            		array4[i]=array3[1];
	            	Log.i("MI ARRAY4", ""+array4[i]);
		            }

		            //Hacer la suma de todos los elementos 
		            ArrayList<Integer> arregloDeNumeros = new ArrayList<Integer>();
		            
		            for(String numeroCadena : array4){
		            	try {
		            		arregloDeNumeros.add(Integer.valueOf(numeroCadena));
						} catch (NumberFormatException e) {
							Log.i("", ""+e.getStackTrace() );
						}	
		            }
		            
		            for(int valor : arregloDeNumeros){
		            	Log.i("FOREACH", "" + valor);
		            	suma += valor;
		            }
		            
		            Log.i("SUMA******", "" + suma);
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
	}
	
	public class CargarInfo extends AsyncTask<String, String, String>{
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(ListaPrecio.this, "",
					"Cargando...", true, true, new OnCancelListener() {
						
						@Override
						public void onCancel(DialogInterface arg0) {
							finish();
						}
			});
		}
		
		
		@Override
		protected String doInBackground(String... params) {
	        Bundle extras=getIntent().getExtras();
			if(extras!=null){
				sb5= extras.getString("sb5");
				content = extras.getString("content");
				bandera = extras.getInt("bandera");
				sb9 = extras.getString("sb9");
			}
			organizararray(sb5);
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
	        data = new Vector<RowData>();
	        Log.i("TAMAÑO 4", ""+array4.length);
	        Log.i("TAMAÑO 2", ""+array2.length);

	        RowData rd1 = new RowData("[Cualquiera]", "("+suma+")");
	        data.add(rd1);
			for (int i = 1; i < array2.length; i++) {
				RowData rd = new RowData(""+array2[i]," ("+array4[i]+") ");
		        data.add(rd);
			}
			CustomAdapter adapter = new CustomAdapter(getApplicationContext(), R.layout.custom_row2,R.id.item, data);
	        setListAdapter(adapter); 
			progressDialog.dismiss();

		}
		
		
	}

	//CHECA LA CONEXION A INTERNET
	public boolean isOnline() {
		NetworkInfo networkInfo = ((ConnectivityManager) getApplicationContext()
	              .getSystemService(Context.CONNECTIVITY_SERVICE))
	              .getActiveNetworkInfo();

	            if(networkInfo == null || !networkInfo.isConnected()) {
	             return false;
	            }
	            return true;
	}
	
	
}
